<template>
  <div class="admin-menus-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>菜单管理</h1>
        <div class="breadcrumb">
          <span>首页</span> / <span class="current">菜单管理</span>
        </div>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showAddMenuDialog">
          <el-icon><Plus /></el-icon>
          添加菜单
        </el-button>
        <el-button @click="refreshMenuList">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-filter-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="菜单名称">
          <el-input v-model="searchForm.name" placeholder="请输入菜单名称" clearable />
        </el-form-item>
        <el-form-item label="菜单类型">
          <el-select v-model="searchForm.type" placeholder="选择菜单类型" clearable style="width: 150px;">
            <el-option label="目录" value="1" />
            <el-option label="菜单" value="2" />
            <el-option label="按钮" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 120px;">
            <el-option label="显示" value="1" />
            <el-option label="隐藏" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchMenus">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="data-table-card">
      <!-- 工具栏 -->
      <div class="toolbar">
        <span class="tool-info">菜单类型：1=目录，2=菜单，3=按钮</span>
        <el-button type="danger" @click="deleteSelectedMenus" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除 ({{ selectedRows.length }})
        </el-button>
      </div>

      <!-- 树形表格 -->
      <el-table
        :data="menuList"
        style="width: 100%"
        border
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
        @selection-change="handleSelectionChange"
        v-loading="loading"
        table-layout="fixed"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="name" label="名称" min-width="150">
          <template #default="scope">
            <div class="menu-name-cell">
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="120">
          <template #default="scope">
            {{ getRoleName(scope.row.roleId) }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 1" size="small" type="primary" class="menu-type-tag">目录</el-tag>
            <el-tag v-else-if="scope.row.type === 2" size="small" type="success" class="menu-type-tag">菜单</el-tag>
            <el-tag v-else-if="scope.row.type === 3" size="small" type="info" class="menu-type-tag">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="路由地址" min-width="150" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(value) => updateMenuStatusLocal(scope.row.id, value)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="showAddMenuDialog(scope.row)"
              :disabled="scope.row.type === 3"
            >
              <el-icon><Plus /></el-icon>
              添加子菜单
            </el-button>
            <el-button size="small" type="success" @click="showEditMenuDialog(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteMenu(scope.row)" :disabled="scope.row.hasChildren || (scope.row.children && scope.row.children.length > 0)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      v-model="menuDialogVisible"
      :title="menuDialogTitle"
      width="600px"
    >
      <el-form :model="menuForm" :rules="menuFormRules" ref="menuFormRef" label-width="100px">
        <el-form-item label="菜单类型" prop="type">
          <el-select v-model="menuForm.type" placeholder="选择菜单类型" @change="handleMenuTypeChange">
            <el-option label="目录" value="1" />
            <el-option label="菜单" value="2" />
            <el-option label="按钮" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="父菜单" prop="parentId">
          <el-cascader
            v-model="menuForm.parentIdPath"
            :options="parentMenuOptions"
            :props="{ checkStrictly: true, emitPath: false }"
            placeholder="选择父菜单"
            @change="handleParentMenuChange"
          />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="menuForm.type !== 3">
          <el-input v-model="menuForm.icon" placeholder="请输入图标名称" />
          <div class="form-hint">提示：使用 Element Plus 图标，如：Menu, User, Setting</div>
        </el-form-item>
        <el-form-item label="路由URL" prop="url" v-if="menuForm.type !== 3">
          <el-input v-model="menuForm.url" placeholder="请输入路由URL" />
          <div class="form-hint">提示：目录和菜单项需要配置路由路径</div>
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="menuForm.type === 2">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
          <div class="form-hint">提示：如：views/user/index.vue</div>
        </el-form-item>
        <el-form-item label="重定向地址" prop="redirect" v-if="menuForm.type === 1">
          <el-input v-model="menuForm.redirect" placeholder="请输入重定向地址" />
          <div class="form-hint">提示：如：/user/list</div>
        </el-form-item>
        <el-form-item label="权限标识" prop="permission">
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识" />
          <div class="form-hint">提示：如：user:view, user:add</div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" :max="999" placeholder="排序" />
        </el-form-item>
        <el-form-item label="是否显示" prop="status">
          <el-switch v-model="menuForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeMenuDialog">取消</el-button>
          <el-button type="primary" @click="submitMenuForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Edit,
  Delete,
  Menu as MenuIcon,
  SetUp
} from '@element-plus/icons-vue'
import { getMenuList, checkMenuHasChildren, addMenu, updateMenu, updateMenuStatus, deleteMenu as deleteSingleMenu, batchDeleteMenus } from '@/api/menu'

// 获取角色名称
const getRoleName = (roleId) => {
  if (!roleId) return '-'    
  return roleId === 1 ? '普通用户' : roleId === 2 ? '管理员' : '-'  
}

// 菜单数据相关
const menuList = ref([])
const selectedRows = ref([])
const currentMenuId = ref(null)
const isAddMode = ref(true)

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 菜单对话框相关
const menuDialogVisible = ref(false)
const menuDialogTitle = ref('添加菜单')
const menuForm = reactive({
  id: '',
  name: '',
  parentId: '0',
  parentIdPath: [],
  type: '1',
  icon: '',
  url: '',
  sort: 0,
})
const menuFormRef = ref(null)
const menuFormRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 1, max: 50, message: '菜单名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  parentId: [
    { required: true, message: '请选择父菜单', trigger: 'change' }
  ],
  url: [
    { required: (rule, value, callback) => {
      if (menuForm.type !== 3 && !value) {
        callback(new Error('请输入路由URL'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  component: [
    { required: (rule, value, callback) => {
      if (menuForm.type === 2 && !value) {
        callback(new Error('请输入组件路径'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' },
    { type: 'number', message: '排序必须是数字', trigger: 'blur' }
  ]
}

// 父菜单选项（用于级联选择器）
const parentMenuOptions = computed(() => {
  const options = []
  
  const buildMenuOptions = (menus, level = 0) => {
    menus.forEach(menu => {
      if (menu.type !== 3) {
        const menuOption = {
          value: menu.id,
          label: menu.name,
          disabled: false
        }
        if (menu.children && menu.children.length > 0) {
          menuOption.children = buildMenuOptions(menu.children, level + 1)
        }
        options.push(menuOption)
      }
    })
    return options
  }
  
  const menuCopy = JSON.parse(JSON.stringify(menuList.value))
  buildMenuOptions(menuCopy)
  
  return options
})

onMounted(() => {
  menuDialogVisible.value = false
  isAddMode.value = true
  currentMenuId.value = null
  resetMenuForm()
  fetchMenuList()
})

const loading = ref(false)

const fetchMenuList = async () => {
  loading.value = true
  try {
    const response = await getMenuList(searchForm)
    menuList.value = response.data || []
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    ElMessage.error('获取菜单列表失败：' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
    // 可选：确保表格重新计算布局（极端情况下）
    await nextTick()
  }
}

// === 其他方法保持不变（searchMenus, resetSearch, refreshMenuList, handleSelectionChange, checkMenuHasChildrenLocal 等）===

const searchMenus = () => {
  fetchMenuList()
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchMenuList()
}

const refreshMenuList = () => {
  fetchMenuList()
}

const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

const checkMenuHasChildrenLocal = async (menuId) => {
  if (!menuId || typeof menuId !== 'number' && !menuId.toString().trim()) {
    console.warn('无效的菜单ID:', menuId)
    return false
  }
  try {
    const response = await checkMenuHasChildren(menuId)
    return response.data || false
  } catch (error) {
    console.error('检查菜单子项失败:', error)
    return false
  }
}

const showAddMenuDialog = (parentMenu = null) => {
  isAddMode.value = true
  menuDialogTitle.value = parentMenu ? `添加「${parentMenu.name}」的子菜单` : '添加菜单'
  resetMenuForm()
  if (parentMenu) {
    menuForm.parentId = parentMenu.id
    menuForm.parentIdPath = [parentMenu.id]
    if (parentMenu.type === 1) {
      menuForm.type = '2'
    } else if (parentMenu.type === 2) {
      menuForm.type = '3'
    }
  }
  menuDialogVisible.value = true
}

const showEditMenuDialog = (menu) => {
  isAddMode.value = false
  menuDialogTitle.value = `编辑菜单：${menu.name}`
  Object.assign(menuForm, {
    id: menu.id,
    name: menu.name,
    parentId: menu.parentId,
    parentIdPath: menu.parentId !== '0' ? [menu.parentId] : [],
    type: String(menu.type),
    icon: menu.icon || '',
    url: menu.url || '',
    component: menu.component || '',
    redirect: menu.redirect || '',
    permission: menu.permission || '',
    sort: menu.sort || 0,
    status: menu.status
  })
  menuDialogVisible.value = true
}

const closeMenuDialog = () => {
  menuDialogVisible.value = false
  resetMenuForm()
}

const resetMenuForm = () => {
  if (menuFormRef.value) {
    menuFormRef.value.resetFields()
  }
  Object.assign(menuForm, {
    id: '',
    name: '',
    parentId: '0',
    parentIdPath: [],
    type: '1',
    icon: '',
    url: '',
    component: '',
    redirect: '',
    permission: '',
    sort: 0,
    status: '1'
  })
}

const handleMenuTypeChange = (type) => {
  if (type === '1') {
    menuForm.component = ''
    menuForm.url = ''
  } else if (type === '2') {
    menuForm.redirect = ''
  } else if (type === '3') {
    menuForm.icon = ''
    menuForm.url = ''
    menuForm.component = ''
    menuForm.redirect = ''
  }
}

const handleParentMenuChange = (value) => {
  if (value && value.length > 0) {
    menuForm.parentId = value[value.length - 1]
  } else {
    menuForm.parentId = '0'
  }
}

const submitMenuForm = async () => {
  if (!menuFormRef.value) return
  try {
    await menuFormRef.value.validate()
    const submitData = {
      ...menuForm,
      parentId: menuForm.parentId
    }
    if (isAddMode.value) {
      const response = await addMenu(submitData)
      if (response.code === 100) {
        ElMessage.success('添加菜单成功')
      } else {
        throw new Error(response.msg || '添加菜单失败')
      }
    } else {
      const response = await updateMenu(submitData)
      if (response.code === 100) {
        ElMessage.success('编辑菜单成功')
      } else {
        throw new Error(response.msg || '编辑菜单失败')
      }
    }
    closeMenuDialog()
    fetchMenuList()
  } catch (error) {
    if (error.name === 'ValidationError') return
    ElMessage.error(`${isAddMode.value ? '添加' : '编辑'}菜单失败：` + error.message)
  }
}

const updateMenuStatusLocal = async (menuId, status) => {
  try {
    const response = await updateMenuStatus(menuId, {
      status: Number(status)
    })
    if (response.code === 100) {
      ElMessage.success('更新菜单状态成功')
    } else {
      throw new Error(response.msg || '更新菜单状态失败')
    }
  } catch (error) {
    ElMessage.error('更新菜单状态失败：' + error.message)
    fetchMenuList()
  }
}

const deleteMenu = async (menu) => {
  try {
    const hasChildrenMenu = await checkMenuHasChildrenLocal(menu.id)
    if (hasChildrenMenu) {
      ElMessage.warning('该菜单下还有子菜单，无法删除')
      return
    }
  } catch (error) {
    console.error('检查子菜单失败:', error)
    ElMessage.error('检查子菜单失败')
    return
  }

  ElMessageBox.confirm(
    `确定要删除菜单「${menu.name}」吗？此操作不可撤销。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteSingleMenu(menu.id)
      if (response.code === 100) {
        ElMessage.success('删除菜单成功')
        fetchMenuList()
      } else {
        throw new Error(response.msg || '删除菜单失败')
      }
    } catch (error) {
      ElMessage.error('删除菜单失败：' + error.message)
    }
  }).catch(() => {})
}

const deleteSelectedMenus = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的菜单')
    return
  }

  try {
    const hasChildrenChecks = await Promise.all(
      selectedRows.value.map(menu => checkMenuHasChildrenLocal(menu.id))
    )
    if (hasChildrenChecks.some(hasChildren => hasChildren)) {
      ElMessage.warning('选择的菜单中包含有子菜单的项，无法批量删除')
      return
    }
  } catch (error) {
    console.error('批量检查子菜单失败:', error)
    ElMessage.error('检查菜单信息失败')
    return
  }

  const menuNames = selectedRows.value.map(menu => menu.name).join('、')
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个菜单吗？\n${menuNames}`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const menuIds = selectedRows.value.map(menu => menu.id)
      const response = await batchDeleteMenus(menuIds)
      if (response.code === 100) {
        ElMessage.success('批量删除菜单成功')
        selectedRows.value = []
        fetchMenuList()
      } else {
        throw new Error(response.msg || '批量删除菜单失败')
      }
    } catch (error) {
      ElMessage.error('批量删除菜单失败：' + error.message)
    }
  }).catch(() => {})
}
</script>

<style lang="scss" scoped>
.admin-menus-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .header-content {
    .breadcrumb {
      color: #606266;
      font-size: 14px;
      margin-top: 8px;
      
      .current {
        color: #409eff;
        font-weight: 500;
      }
    }
  }
  
  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.search-filter-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .search-form {
    .el-form-item {
      margin-right: 10px;
    }
  }
}

.data-table-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  min-height: 400px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .tool-info {
    color: #606266;
    font-size: 14px;
  }
}

.menu-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

@media (max-width: 768px) {
  .admin-menus-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-filter-card {
    .search-form {
      .el-form-item {
        margin-right: 0;
        margin-bottom: 15px;
        width: 100%;
      }
    }
  }
  
  .toolbar {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}

/* 👇 关键：修复表格对齐与铺满 */
::v-deep(.el-table) {
  table-layout: fixed !important;
  width: 100% !important;

  th,
  td {
    padding-left: 12px !important;
    padding-right: 12px !important;
    box-sizing: border-box !important;
  }

  .cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>